<template>
  <div class="pickers">
      <van-button type="default" icon="arrow-down" round block size="small" plain :text="area !== '' ? area : '请选择区域'" @click="show=true"></van-button>
      <van-popup v-model="show" position="bottom" :overlay="true" closeable round
          :style="{ height: '50%' }">
          <van-picker show-toolbar title="请选择区域" :columns="areas" :default-index="0"
             @confirm="show=false" @cancel="show = false" @change="onChange" ref="picker"/>
      </van-popup>
  </div>
</template>

<script>
import dict from "@/modules/freestay/api/dict";
import { mapState } from 'vuex'
import { Toast } from "vant";

export default {
  props:['areaName'],
  data() {
    return {
      show: false,
      area: '全部'
    };
  },
  watch: {
    areaName (newValue, oldValue) {
        this.area = newValue;
        this.$refs.picker.setValues([newValue])
    },
  },
  mounted() {
    // if(this.$store.state.areas.length==0)
    //   this.initData();
    // else {
    //   this.areas = this.$store.state.areas;
    //   this.area = this.areas[0].text;
    // }
  },
  computed: mapState({
    areas: state => state.common.areas
  }),
  created () {
    this.$store.dispatch('common/getAreas')
  },
  methods: {
    onChange(picker, value, index) {
        this.show = false;
        this.area = value.text;
        this.$store.state.areaValue = value.id;
        this.$emit('selectedArea',value.id);
    },
    // 初始化必要的数据this
    initData() {
      dict.getAreas(
        res => {
          if(res.data.code==200) {
            this.areas = [{text:'全部',id:0}];
            var data = res.data["Dicts[]"]
            for(var i in data)
              this.areas.push({text:data[i].text,id:data[i].id});     
            this.area = '全部';
            this.$store.state.areas = this.areas;
          }
          else
            Toast('加载区域信息失败!');
        },
        err => {
            Toast('加载区域信息失败:'+error);
        });

    },
  },
};
</script>
<style scoped>
.pickers {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.van-button__text {
  max-width: 10em;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.van-button {
    margin-left: 5px;
}
</style>
